package com.itheima.controller;

import com.alibaba.fastjson.JSON;
import com.github.pagehelper.StringUtil;
import com.itheima.entity.Result;
import com.itheima.utils.HttpUtils;
import org.apache.ibatis.annotations.Param;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;


import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.util.Map;

@RestController
@RequestMapping("weChat")
public class Test {
    @Autowired
    private JedisPool jedisPool;

    /**
     * 获取授权
     *
     * @param code
     */
    @RequestMapping("getToken")
    public Result getToken(@Param("code") String code, HttpSession session) {
        String url = "https://api.weixin.qq.com/sns/oauth2/access_token?appid=wx6ab7574b2416b77f&secret=b5ca96a7b394c7bab69569151bd5028b&code=" + code + "&grant_type=authorization_code";
        String s = HttpUtils.doGet(url);

        Map<String, String> map = (Map) JSON.parse(s);
        String accessToken = map.get("access_token");
        String refreshToken = map.get("refresh_token");
        String openid = map.get("openid");
        Jedis jedis = jedisPool.getResource();
        try {
            System.out.println("将access_token和refresh_token添加到数据库=========================================");

            jedis.setex("wxuser_" + openid, 6200, accessToken + "___" + refreshToken);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            jedis.close();
        }
        Map userMap = getUser(accessToken, openid);
        session.setAttribute("userData", userMap);
        return Result.success("登录成功", userMap);
    }

    /**
     * 获取用户信息
     *
     * @param accessToken
     * @param openid
     * @return
     */
    /*{
      "openid":" OPENID",
      "nickname": NICKNAME,
      "sex":"1",
      "province":"PROVINCE",
      "city":"CITY",
      "country":"COUNTRY",
      "headimgurl":"https://thirdwx.qlogo.cn/mmopen/g3MonUZtNHkdmzicIlibx6iaFqAc56vxLSUfpb6n5WKSYVY0ChQKkiaJSgQ1dZuTOgvLLrhJbERQQ4eMsv84eavHiaiceqxibJxCfHe/46",
      "privilege":[ "PRIVILEGE1" "PRIVILEGE2"     ],
      "unionid": "o6_bmasdasdsad6_2sgVt7hMZOPfL"
    }*/
    private Map getUser(String accessToken, String openid) {

        String url = "https://api.weixin.qq.com/sns/userinfo?access_token=" + accessToken + "&openid=" + openid + "&lang=zh_CN";

        String s = HttpUtils.doGet(url);
        Map<String, String> map = (Map) JSON.parse(s);

        return map;
    }

    /**
     * 根据 refresh_token 刷新 accessToken 和 RefreshToken
     *
     * @param refresh_token
     */
    private void updateToken(String refresh_token) {
        String url = "https://api.weixin.qq.com/sns/oauth2/refresh_token?appid=wx6ab7574b2416b77f&grant_type=refresh_token&refresh_token=" + refresh_token;
        String s = HttpUtils.doGet(url);

        Map<String, String> map = (Map) JSON.parse(s);
        String accessToken = map.get("access_token");
        String refreshToken = map.get("refresh_token");
        String openid = map.get("openid");

        Jedis jedis = jedisPool.getResource();
        try {
            System.out.println("刷新access_token和refresh_token=========================================");

            jedis.setex("wxuser_" + openid, 6200, accessToken + "___" + refreshToken);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            jedis.close();
        }
    }

//    public String setUserRemark(Long userId) {
//        //
//        User user = this.findUser(userId);
//        String openId = user.getOpenId();
//        String accessTokenAndRefresh = jedisPool.getResource().get("wxuser_" + openId);
//        String[] s = accessTokenAndRefresh.split("___");
//        s[0];
//        s[1];
//        //https://api.weixin.qq.com/cgi-bin/user/info/updateremark?access_token=ACCESS_TOKEN
//
//    }

    @RequestMapping("login")
    public Result login(HttpServletResponse response, HttpSession session) {
        Map map = (Map) session.getAttribute("userData");
        if (map != null) {
            String openid = (String) map.get("openid");
            if (!StringUtil.isEmpty(openid)) {
                Jedis jedis = jedisPool.getResource();
                String s = jedis.get("wxuser_" + openid);
                String[] strings = s.split("___");

                System.out.println("通过access_token登录================================");
                Map userMap = getUser(strings[0], openid);
                return Result.success("登录成功", userMap);
            }
        }
        System.out.println("获取授权=====================================");
        String url = "https://open.weixin.qq.com/connect/oauth2/authorize?appid=wx6ab7574b2416b77f&redirect_uri=http%3a%2f%2fgpyhealth.utools.club%2fweChat%2fgetToken.do&response_type=code&scope=snsapi_userinfo#wechat_redirect";
        try {
            response.sendRedirect(url);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }
}